package com.labot.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.labot.Constants;

import org.springframework.context.i18n.LocaleContextHolder;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;


public final class DateUtil {
	
	public static String PATTERN_FECHA_MONTH_NAME = "dd/MMM/yyyy";
	public static String PATTERN_HORA = "hh:mm aa";
	public static String HIDALGO_PATTERN_FECHA_HORA = PATTERN_FECHA_MONTH_NAME + " " + PATTERN_HORA;
	public static String PATTERN_FECHA = "dd/MM/yyyy";
	public static String SQL_FECHA = "yyyy-MM-dd";
	public static String SQL_FECHA_HORA = "yyyy-MM-dd HH:mm:ss";
	public static String HIDALGO_FECHA_DBF = "EEE MMM dd HH:mm:ss zzz yyyy";
	
    private static Log log = LogFactory.getLog(DateUtil.class);
    private static final String TIME_PATTERN = "HH:mm";

    /**
     * Checkstyle rule: utility classes should not have public constructor
     */
    private DateUtil() {
    }

    /**
     * Return default datePattern (MM/dd/yyyy)
     *
     * @return a string representing the date pattern on the UI
     */
    public static String getDatePattern() {
        Locale locale = LocaleContextHolder.getLocale();
        String defaultDatePattern;
        try {
            defaultDatePattern = ResourceBundle.getBundle(Constants.BUNDLE_KEY, locale)
                    .getString("date.format");
        } catch (MissingResourceException mse) {
            defaultDatePattern = "MM/dd/yyyy";
        }

        return defaultDatePattern;
    }

    public static String getDateTimePattern() {
        return DateUtil.getDatePattern() + " HH:mm:ss";
    }

    /**
     * This method attempts to convert an Oracle-formatted date
     * in the form dd-MMM-yyyy to mm/dd/yyyy.
     *
     * @param aDate date from database as a string
     * @return formatted string for the ui
     */
    public static String getDate(Date aDate) {
        SimpleDateFormat df;
        String returnValue = "";

        if (aDate != null) {
            df = new SimpleDateFormat(getDatePattern());
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }

    /**
     * This method generates a string representation of a date/time
     * in the format you specify on input
     *
     * @param aMask the date pattern the string is in
     * @param strDate a string representation of a date
     * @return a converted Date object
     * @throws ParseException when String doesn't match the expected format
     * @see java.text.SimpleDateFormat
     */
    public static Date convertStringToDate(String aMask, String strDate)
            throws ParseException {
        SimpleDateFormat df;
        Date date;
        df = new SimpleDateFormat(aMask);

        if (log.isDebugEnabled()) {
            log.debug("converting '" + strDate + "' to date with mask '" + aMask + "'");
        }

        try {
            date = df.parse(strDate);
        } catch (ParseException pe) {
            //log.error("ParseException: " + pe);
            throw new ParseException(pe.getMessage(), pe.getErrorOffset());
        }

        return (date);
    }

    /**
     * This method returns the current date time in the format:
     * MM/dd/yyyy HH:MM a
     *
     * @param theTime the current time
     * @return the current date/time
     */
    public static String getTimeNow(Date theTime) {
        return getDateTime(TIME_PATTERN, theTime);
    }

    /**
     * This method returns the current date in the format: MM/dd/yyyy
     *
     * @return the current date
     * @throws ParseException when String doesn't match the expected format
     */
    public static Calendar getToday() throws ParseException {
        Date today = new Date();
        SimpleDateFormat df = new SimpleDateFormat(getDatePattern());

        // This seems like quite a hack (date -> string -> date),
        // but it works ;-)
        String todayAsString = df.format(today);
        Calendar cal = new GregorianCalendar();
        cal.setTime(convertStringToDate(todayAsString));

        return cal;
    }

    /**
     * This method generates a string representation of a date's date/time
     * in the format you specify on input
     *
     * @param aMask the date pattern the string is in
     * @param aDate a date object
     * @return a formatted string representation of the date
     * @see java.text.SimpleDateFormat
     */
    public static String getDateTime(String aMask, Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";

        if (aDate == null) {
            log.warn("aDate is null!");
        } else {
            df = new SimpleDateFormat(aMask);
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }

    /**
     * This method generates a string representation of a date based
     * on the System Property 'dateFormat'
     * in the format you specify on input
     *
     * @param aDate A date to convert
     * @return a string representation of the date
     */
    public static String convertDateToString(Date aDate) {
        String data = getDateTime(getDateTimePattern(), aDate);
        //check if data contains 00:00:00 remove...
        if (data.contains(" 00:00:00")) {
        	data = data.split(" ")[0];
        }
        return data;
    }

    /**
     * This method converts a String to a date using the datePattern
     *
     * @param strDate the date to convert (in format MM/dd/yyyy)
     * @return a date object
     * @throws ParseException when String doesn't match the expected format
     */
    public static Date convertStringToDate(final String strDate) throws ParseException {
    	if (strDate.contains(" ") && strDate.contains(":")) {
    		return convertStringToDate(getDateTimePattern(), strDate);
    	}
        return convertStringToDate(getDatePattern(), strDate);
    }
    
    
    //New Methods
    
    /**
	 * Devuelve la diferencia de minutos entre 2 fechas
	 * @param start
	 * @param end
	 * @return
	 */
	public static Integer diffMinutesBetweenDates(Date start, Date end) {
	      
		long from = start.getTime();
	    long to = end.getTime();
	    double difference = to - from;
	    long minutes = Math.round((difference/(1000*60)));
	    return new Integer(""+minutes);
	    
	}
	
	/**
	 * Devuelve la diferencia de segundos entre 2 fechas
	 * @param start
	 * @param end
	 * @return
	 */
	public static Integer diffSecondsBetweenDates(Date start, Date end) {
	      
		long from = start.getTime();
	    long to = end.getTime();
	    double difference = to - from;
	    long minutes = Math.round((difference/(1000)));
	    return new Integer(""+minutes);
	    
	}
	
	public static String dateToString(Date date, String pattern) {
		SimpleDateFormat sim = new SimpleDateFormat(pattern, new Locale("es_ES"));
		return sim.format(date);
	}
	
	
	public static Date parseDate (String date, String pattern) throws Exception {
		SimpleDateFormat sim = new SimpleDateFormat(pattern, new Locale("es_ES"));
        return sim.parse(date);
		
	}
}
